import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/card_info_entity.dart';
import 'package:nyh_motorcade_app/entity/driver_details_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';

class DriverDetailsController extends GetxController {
  List<String> tabTitle = [];
  MultiState multiState = MultiState.loading;
  String driverId = "";
  DriverDetailsEntity? entity;
  List<CardInfoItem> cardList = [];

  @override
  void onReady() {
    driverId = Get.arguments ?? "";
    getDriverDetails();
  }

  Future<void> onRefresh() async {
    getDriverDetails();
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getDriverDetails();
  }

  void goBackHomePage() {
    Get.until((route) => Get.currentRoute == Routes.main);
  }

  Future<void> goToEditDriverInfoPage() async {
    if (entity == null) {
      return;
    }
    dynamic data = await Get.toNamed(Routes.addDriver, arguments: {Constant.PARAM_ENTITY: entity, Constant.PARAM_IS_RETURN: true});
    if (data != null) {
      multiState = MultiState.loading;
      update();
      getDriverDetails();
    }
  }

  void goToTransactionFlowPage() {
    Get.toNamed(Routes.transactionFlow, arguments: {Constant.PARAM_TYPE: Constant.DRIVER, Constant.PARAM_SOURCE_ID: driverId});
  }

  void getDriverDetails() {
    httpManager.post(
      Get.context,
      HttpAddress.GET_DRIVER_DETAILS,
      {"id": driverId},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          multiState = MultiState.fail;
          update();
          return;
        }
        entity = DriverDetailsEntity().fromJson(data);
        tabTitle = entity!.ifCardModel == 1 ? ["车辆信息", "卡账户信息"] : ["车辆信息"];
        cardList = entity!.cardList ?? [];
        multiState = MultiState.success;
        update();
      },
      onFail: (code, msg) {
        multiState = MultiState.fail;
        update();
      },
      onError: (msg) {
        multiState = MultiState.error;
        update();
      },
    );
  }

  void setEnableEdit(bool isEnable) {
    if (entity != null) {
      entity!.enableEdit = isEnable;
    }
  }
}
